define(function(require, exports, module){
	require("oa/act/js/loading.js");
	var alertMsg = require("resource/js/component/alerts.js");
	var check = require('resource/js/component/check.js');
	var ajax = require("resource/js/component/ajax.js");
	//遮罩
	function showLoading() {
		$('body').loading({msg:'提交中'});
	}

	function hideLoading() {
		$('body').loading('hide');
	}
	function checkApprover(approverList){

	}
	exports.checkApprover = function (approverList){
		var isEmpty = true;
		var isFull = true;

		//code:0校验成功，1审核人为空，2审核人设置不完整
		var code = 0;
		var msg = "ok";
		var result = {code:code,msg:msg,data:null};
		if($("#processNodeId").val() == 'PROCESS_START'){
			var list = approverList;
			if(list && list.length > 0){
				for(var i=0;i<list.length;i++){
					if(list[i]==undefined){
						isFull = false;
						continue;
					}else{
						isEmpty = false;
					}
				}
			}
			var startUser = $('#currentUserId').val().toString()
			var startNode = {nodeId:"PROCESS_START",orderNum:0,userType:"userId","userId":startUser,"approveStatus":0};
			list.push(startNode);
			result.data = list;
			if(isEmpty){
				result.code = 1;
				result.msg = "至少设置一个审核人！";
				return result;
			}
			if(!isFull){
				result.code = 2;
				result.msg = "您的审核人设置不完整";
				return result;
			}
		}
		return result;
	};
	exports.checkForm =function (btnObj,approverList){
		var ok = true;	//校验通过标志
		$('#btnsWarp').find('.easyui-linkbutton ').linkbutton("disable");

		//取出流程参数
		var processDatas = $(btnObj).data('options');
		var processData={};
		var callbackJs;
		if(processDatas&&processDatas!=""){
			if(typeof processDatas == 'object'){
				processData=processDatas;
			}else if(typeof processDatas == 'string'){
				processData=eval('(' + processDatas+ ')');
			}

		}
		//1.easyui校验
		if(ok){
			ok = $(".processForm").form('validate');
			ok && (ok = $(".subsForm").form('validate'));
			ok &&( ok = $(".subsTabForm").form('validate'))
		}
		//2.流程内置JS校验
		if(ok){
			if(processData!=null && processData.hasOwnProperty("submitJs")){
				var js = processData.submitJs;
				if(js!=null&&js!=""){
					js = js.replace(/\^/g,"\"");
					js = js.replace(/\~/g,"'");
					eval("var temp ="+js);
					ok = temp(alertMsg,'0',ajax);
				}
			}
		}
		//3.封装主表单数据
		var main = {};
		if(ok){
			ok = chechInput($(".processForm").find(".textbox-text"),main)
			var hidden = $(".processForm").find("input").filter(".processHidden");
			$.each(hidden,function(i,input){
				packageData($(input).attr("id"),$(input).val(),main);
			});
		}
		//4.封装子表单数据
		var subs = {};
		var subsForm = {};
		if(ok){
			ok=chechInput($(".subsForm").find(".textbox-text"),subsForm);
			if(ok){
				hidden = $(".subsForm").find("input").filter(".processHidden");
				$.each(hidden,function(i,input){
					packageData($(input).attr("id"),$(input).val(),subsForm);
				});
			}
			var tabs = $("table[sign='processTable']");
			if(tabs&&tabs.length>0){
				$.each(tabs,function(i,tab){
					ok = checkTable($(tab).attr("id"),subs);
					if(!ok){
						return false;
					}
				});
			}
			$.each(subsForm,function(key,val){
				if(val.data){
					var temp =[];
					temp.push(val.data);
					val.data=temp;
				}
			});
			$.extend(true,subs,subsForm)
		}

		//5.组合form
		if(ok){
			main = getProcessCols(main,"mainIsProcess");
			subs = getProcessCols(subs,"subIsProcessForm");
			subs = getProcessCols(subs,"subIsProcessTable");
			//提交数据
			addPro(main);
			addPro(subs);

			var ccUsers = "";
			if($("#copyOfUsers").val()){
				$.each(JSON.parse($("#copyOfUsers").val()),function(i,val){
					ccUsers+=val+','
				});
				ccUsers=ccUsers.substr(0,ccUsers.length-1);
			}
			var sealPath = $('#seal').val() || null;
			var signPath = $('#sign').val() || null;
			var assignUserId = $("#assign-UserId").val()|| null;
			var processDataParam
			if(processData!=null&&processData.hasOwnProperty("param")){
				processDataParam = processData.param;
			}
			var info = {
			    	key:$("#processKey").val(),
			    	processNodeId:$("#processNodeId").val(),
			    	processInstanceId:$("#processInstanceId").val(),
			    	taskId:$("#taskId").val(),
			    	busenessId:$("#busenessId").val(),
			    	action:$(btnObj).linkbutton('options').text||'提交',
			    }
			assignUserId && (info.assignUserId = assignUserId);
			sealPath && (info.seal = sealPath);
			signPath && (info.sign = signPath);

			var result = {
					info:info,
					main:main,
					subs:subs
				};
			ccUsers && (result.ccUsers = {ccUsers:ccUsers});
			approverList && (result.approverList = {approvers:approverList});
			processDataParam && (result.processDataParam = processDataParam);

		}
		$('#btnsWarp').find('.easyui-linkbutton ').linkbutton('enable');
		return result || ok;
	}

	exports.submitForm = function(obj,data){
		if(data == null){
			return
		}
		//获取流程配置的回掉函数
		var callbackJs;
		var processDatas = $(obj).data('options');
		if(processDatas&&processDatas!=""){
			if(typeof processDatas == 'string'){
				processDatas=eval('(' + processDatas+ ')');
			}
			if(processDatas.hasOwnProperty("callback")){
				callbackJs = processDatas.callback;
				if(callbackJs!=null&&callbackJs!=""){
					callbackJs = callbackJs.replace(/\^/g,"\"");
					callbackJs = callbackJs.replace(/\~/g,"'");
				}
			}
		}
		require.async ('resource/js/component/ajax.js',function(ajax){
			var processInstanceId=$("#processInstanceId").val();
			showLoading();
			ajax.init().success(function(code,msg,data){
				$(obj).parent().find('.easyui-linkbutton ').linkbutton('enable');
				hideLoading();
				if(processInstanceId==null||processInstanceId==""){//首次发起任务
					if(callbackJs){
						eval("var callback ="+callbackJs);
					    callback();
					}else{
						window.location.reload();
					}
				}else{//处理任务后关闭页签并刷新待办任务页签
					window.parent.$('.close').click();
					window.parent.$('.group-line').find('a').first().click();
				}
				window.parent.$.messager.show("系统通知","提交成功");
			}).error(function(code,msg,datas){
				hideLoading();
				alertMsg.alert(msg);
			})
			.contentType('application/json')
			.post(BASEPATH+'/oa/act/activitiMain/saveProcessData.htm',JSON.stringify(data));
		});
	}

	//添加其他需要的属性
	function addPro(data){
		$.each(data,function(key,val){
			var operType= $("#tab-"+key).val();
			data[key].operType=operType;
		});
	}
	//删除 object
	function deleteObj(obj){
		$.each(obj,function(key,val){
			delete obj[key];
		});
	}
	//封装数据
	function packageData(id,val,data){
		var table = id.split('-')[0];
		var name = id.split('-')[1];
		if(!data[table]){
			data[table]={};
		}
		data[table].tab=table;
		if(!data[table].data){
			data[table].data={};
		}
		data[table].data[name]=val;
	}
	//验证数据是否合法 合法则封装数据
	function chechInput(ins,data,check){
		var ok = true;
		$.each(ins,function(i,input){
			var opt;
			if($.data(input).validatebox){
				opt = $.data(input).validatebox.options;
			}else if($.data(input).textbox){
				opt = $.data(input).textbox.options;
			}else{
				opt = eval('('+$(input).data().options+')');
			}
			var isRequire = opt.isRequire;
			var colNameCh = opt.colNameCh;
			var checkType = opt.checkType;
			var validType = opt.validType;
			var showType = opt.showType;
			var id = opt.id;
			//var val = $("input[name='"+id+"']").val(); 多选下拉菜单只能获取到一个value
			var val ='';
			$("input[name='"+id+"']").each(function(){
				val += $(this).val()+',';
			});
			val = val.substring(0,val.length-1);
			if(showType === 'sign'){
				if(!(val.length > 0)){
					alertMsg.show('提交审批需要签名');
					ok=false;
					return false;
				}
			}
//			if(check){
//				if(!checkVal(isRequire,id,checkType,val)){
//					deleteObj(data);
//					if(isRequire=='0'&&(checkType==''||checkType=='notNull')){
//						alertMsg.alert(colNameCh+"不能为空！");
//						return false;
//					}else if(checkType=='positive' && parseFloat(val) <= 0 ){
//						alertMsg.alert(colNameCh+"必须大于0！");
//						return false;
//					}
//				}
//				//检验数字长度int类型不能超过10位
//				if(checkType=='integer'&&val.length>10||showType=='integer'&&val.length>10){
//					alertMsg.alert(colNameCh+"数字位数超过10位！");
//					return false;
//				}
//				if(checkType=='integer'&&parseInt(val)>2147483647||showType=='integer'&&parseInt(val)>2147483647){
//					alertMsg.alert(colNameCh+"最大值为2147483647！");
//					return false;
//				}
//				if(checkType=='integer'&&parseInt(val)<0||showType=='integer'&&parseInt(val)<0){
//					alertMsg.alert(colNameCh+"值必须大于0！");
//					return false;
//				}
//				//浮点类型不能超过10位
//				if(showType=='number'&&val.length>10){
//					alertMsg.alert(colNameCh+"数字位数超过10位！");
//					return false;
//				}
//				if(validType!=null&&validType.indexOf("maxlength")>=0){
//					var sInd = validType.indexOf("[");
//					var maxlength = validType.substring(sInd+1,validType.length-1);
//					if(val.length>maxlength){
//						alertMsg.alert(colNameCh+"数据超过最大长度"+maxlength+"！");
//						return false;
//					}
//				}
//			}
			packageData(id,val,data);
		});
		return ok;
	}
	//根据是否必填，以及验证类型校验数据是否合法  合法返回true
	function checkVal(isRequire,id,checkType,val){
		if(checkType&&checkType!=''){
			if(check.check(id,checkType,val)){
				return true;
			}else{
				return false;
			}
		}
		if(isRequire=='0'){
			if(!(checkType&&checkType!='')){
				if(check.check(id,'notNull',val)){
					return true;
				}else{
					return false;
				}
			}
		}
		return true;
	}
	//检查子数据 并封装
	function checkTable(tableId,subs,check){
		if(!subs[tableId]){
			subs[tableId]={};
		}
		subs[tableId].tab=tableId;
		subs[tableId].data=[];
		var dg = $("#"+tableId);
		var rows = dg.datagrid("getRows");
		var columns = dg.datagrid("options").columns[0];
		var ok = true;
		$.each(rows,function(i,row){
			var index =  dg.datagrid("getRowIndex",row);
			var rowData={};
			$.each(columns,function(j,con){
				var isRequire = con.isRequire_;
				var colNameCh = con.title;
				var checkType = con.checkType_;
				var showType = con.showType_;
				var id = con.field;
				var ed = dg.datagrid("getEditor",{index:index,field:id});
				var val = $(ed.target).textbox("getValue");
//				if(check){
//					if(!(checkVal(isRequire,id,checkType,val))){
//						if(isRequire=='0'&&(checkType==''||checkType=='notNull')){
//							alertMsg.alert("第"+(index+1)+"行的"+colNameCh+""+"不能为空！");
//						}else{
//							alertMsg.alert("第"+(index+1)+"行的"+colNameCh+""+colNameCh+"数据不合法！");
//						}
//						deleteObj(subs);
//						return false;
//					}else{
//						if(("text" === showType || "textarea" === showType)&&val.length > parseInt(con.colLength_)/2){
//							alertMsg.alert("第"+(index+1)+"行的"+colNameCh+"最大字符长度是"+con.colLength_/2+"！");
//							return false;
//						}else if("number"===showType&&val.length>10){
//							alertMsg.alert("第"+(index+1)+"行的"+colNameCh+"数字位数超过10位！");
//							return false;
//						}else if("number"===showType&&parseFloat(val)<0){
//							alertMsg.alert("第"+(index+1)+"行的"+colNameCh+"值必须大于0！");
//							return false;
//						}else if("integer"===showType&&val.length>10){
//							alertMsg.alert("第"+(index+1)+"行的"+colNameCh+"数字位数超过10位！");
//							return false;
//						}else if(checkType==='integer'&&parseInt(val)>2147483647||showType==='integer'&&parseInt(val)>2147483647){
//							alertMsg.alert("第"+(index+1)+"行的"+colNameCh+"最大值为2147483647！");
//							return false;
//						}else if(checkType==='integer'&&parseInt(val)<0||showType==='integer'&&parseInt(val)<0){
//							alertMsg.alert("第"+(index+1)+"行的"+colNameCh+"值必须大于0！");
//							return false;
//						}
//						rowData[id]=val;
//					}
//				}
				rowData[id]=val;
			});
			subs[tableId].data.push(rowData);
		});
		return true;
	}
	function isInteger(obj) {
	    reg = /^[-+]?\d+$/;
	    if (!reg.test(obj) || obj < 0) {
	        return false;
	    } else {
	        return true;
	    }
	}
	//组合流程参数
	function getProcessCols(data,inputId){
		if(data==null||data==""){
			return data;
		}
		var isProcess = '';
		$.each($("."+inputId),function(){
			var val = $(this).val();
			isProcess += val;
		});
		if(isProcess!=null&&isProcess.length>0){
			isProcess=isProcess.substr(0,isProcess.length-1);
			var is = isProcess.split(",");
			for(var i =0 ;i<is.length;i++){
				var tab = is[i].split('-');
				if(tab.length==2){
					if(typeof (data[''+tab[0]+'']) != 'undefined'){
						if(typeof (data[''+tab[0]+''].cols) == 'undefined'){
							data[''+tab[0]+''].cols=[];
						}
						data[''+tab[0]+''].cols.push(tab[1]);
					}
				}
			}
			return data;
		}else{
			return data;
		}
	}
});
